<!DOCTYPE html>
<html>
<head>
	<title>编辑上报</title>
  <!--Import Google Icon Font-->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <!--Import materialize.css-->
  <link type="text/css" rel="stylesheet" href="/css/materialize.min.css"  media="screen,projection"/>
  <style type="text/css">
  	.report-add{
  		margin-top: 1rem;
  	}
  	.warning-totast{
  		border-radius:8px;
  		background-color: #ee6e73;
  		position: fixed;
  		width: 50%;
  		left: 25%;
  		margin-top: 50%;
  	}
  	.item-add{
  		position: fixed;
  		right: 10px;
  		bottom: 10px;
  	}
  	.project-list{
  		position: relative;
  	}
  </style>
  <!--Let browser know website is optimized for mobile-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>

<body>
	<nav style="background-color: #26a69a;">
    <div class="nav-wrapper">
      <a href="/" class="brand-logo right"><img src="<?=$user['avatar']?>" alt="" style="width: 40px;vertical-align: text-top;" class="circle responsive-img"></a>
      <a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">menu</i></a>
      <ul class="sidenav" id="mobile-demo">
	    <li><a href="/users">员工</a></li>
	    <li><a href="/projects">项目</a></li>
	    <li><a href="/report">上报</a></li>
	    
	  </ul>
    </div>
  </nav>
   
	<div class="container">


	  <div class="row report-add">
	    <form class="col s12">
	      <div class="row">
	        <div class="input-field col s12">
	          <input value="<?=$report['riqi']??''?>" id="riqi" type="text" class="datepicker validate" required>
	          <label for="name">日期</label>
	          <input type="hidden" id="id" value="<?=$report['id']??''?>">
	        </div>
	      </div>
	      
	      <div class="project-list">
	      	<div class="append-wrap">
	      		<?php if(isset($report['id'])):?>

	      			<?php foreach ($details as $value): ?>
	      			<div class="row">
			        <div class="input-field col s8">
			          <select class="project">
					      <option value="" disabled>选择项目</option>
					      <?php foreach($projects as $item):?>
					      	<option <?php 
					      	if($value['project_id']==$item['id']){
					      		echo "selected";
					      	}
					      ?> value="<?=$item['id']?>"><?=$item['name']?></option>
					      <?php endforeach;?>
					    </select>
					    <label>项目</label>
			        </div>
			        <div class="input-field col s4">
			          <input value="<?=$value['hours']??''?>" id="hours<?=$value['id']?>" type="number" min="0.1" step="0.1" max="8" class="validate hours" required>
			          <label for="hours<?=$value['id']?>">工时</label>	          
			        </div>		               
			        <div class="input-field col s10">
			          <input value="<?=$value['memo']??''?>" id="memo<?=$value['id']?>" type="text" class="validate memo" required>
			          <label for="memo<?=$value['id']?>">详情</label>	          
			        </div>		
			      	 <div class="input-field col s2">
				        	<a class="btn-floating waves-effect waves-light btn-remove red"><i class="material-icons">remove</i></a>
				        </div> 
			      </div>
			      <?php endforeach; ?>

	      		<?php else:?>
		      	<div class="row">
			        <div class="input-field col s8">
			          <select class="project">
					      <option value="" disabled selected>选择项目</option>
					      <?php foreach($projects as $item):?>
					      	<option value="<?=$item['id']?>"><?=$item['name']?></option>
					      <?php endforeach;?>
					    </select>
					    <label>项目</label>
			        </div>
			        <div class="input-field col s4">
			          <input value="" id="hours" type="number" min="0.1" step="0.1" max="8" class="validate hours" required>
			          <label for="hours">工时</label>	          
			        </div>		               
			        <div class="input-field col s10">
			          <input value="" id="memo" type="text" class="validate memo" required>
			          <label for="memo">详情</label>	          
			        </div>		
			      	 <div class="input-field col s2">
				        	<a class="btn-floating waves-effect waves-light btn-remove red"><i class="material-icons">remove</i></a>
				        </div> 
			      </div>
			    	<?php endif;?>
		      </div>
	      	<a class="btn-floating waves-effect waves-light" onclick="return addItem();"><i class="material-icons">add</i></a>
	      </div>

	       <div class="row" style="text-align: center;">
	       	<button class="btn waves-effect waves-light" onclick="return editUser();" type="button" name="action">保存
    <i class="material-icons right">edit</i>
  </button>
	       </div>
	    </form>
		  
	  </div>
        






       
    </div>

	

  <!--JavaScript at end of body for optimized loading-->
  <script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  <script type="text/javascript" src="/js/materialize.min.js"></script>
  <script type="text/javascript">
  	var append = '<div class="input-field col s8"><select class="project project-1"><option value="" disabled="" selected="">选择项目</option><?php foreach($projects as $item):?><option value="<?=$item['id']?>"><?=$item['name']?></option><?php endforeach;?></select> 					    <label>项目</label> 			        </div> 			        <div class="input-field col s4"> 			          <input value="" class="hours validate" id="hours-1" type="number" min="0.1" step="0.1" max="8" required> 			          <label for="hours-1">工时</label>	          			        </div>		               			        <div class="input-field col s10"> 			          <input value="" class="memo validate" id="memo-1" type="text" required> 			          <label for="memo-1">详情</label>	          			        </div>		 			      	 <div class="input-field col s2"> 				        	<a class="btn-floating waves-effect waves-light btn-remove red"><i class="material-icons">remove</i></a> 				        </div>';


  	function addItem(){
  		let wrap = document.querySelector('.append-wrap');
  		let id = '-'+new Date().getTime();
  		let div = document.createElement("div");
  		div.classList.add('row');
  		div.innerHTML = append.replace(/-1/g,id);
  		wrap.appendChild(div);
  		M.FormSelect.init(document.querySelectorAll(`.project${id}`));
  	}

  	$('.append-wrap').on('click','.btn-remove',function(){
  		$(this).parent().parent().remove();
  	});

  	function M_info(msg,url=''){
  		M.toast({html:msg, classes: 'warning-totast',displayLength:2000});
  		if(url){
  			setTimeout(()=>{
  				window.location.href = url;
  			},2200);
  		}
  	}

  	function M_success($msg,url=''){
  		M.toast({html: $msg, classes: 'warning-totast M_success',displayLength:2000});
  		if(url){
  			setTimeout(()=>{
  				window.location.href = url;
  			},2200);
  		}
  	}

  	function editUser() {
  		let base =  new FormData();
  		base.append('id',document.querySelector('#id').value);
  		base.append('riqi',document.querySelector('#riqi').value);
  		let rows = $('.append-wrap .row');
  		let details = [];
  		for (var i = rows.length - 1; i >= 0; i--) {
  			let project_id = $(rows[i]).find('.project').val();
  			let hours = $(rows[i]).find('.hours').val();
  			let memo = $(rows[i]).find('.memo').val();
  			if(!project_id){
  				M_info('请选择项目!');
  				return false;
  			}
  			if(hours<=0){
  				M_info('请填写工时!');
  				return false;
  			}
  			if(hours>8){
  				M_info('请填写工时(0~8)!');
  				return false;
  			}
  			if(!memo){
  				M_info('请填写详情!');
  				return false;
  			}
  			details.push({project_id,hours,memo});
  		}
  		if(!details.length){
  			M_info('请填写项目明细!');
  			return false;
  		}
  		base.append('details',JSON.stringify(details));
  		if(!base.get('riqi')){
  			M_info('请选择日期!');
  			return false;
  		}
  		
  		fetch('/report/edit', {
		    method: 'post',
		    body: base,
		  }).then(function(response) {
			  return response.json();
			}).then(data => {
				if(data.code!=200){
					M_info(data.message);
				}else{
					M_success('操作成功','/report');
				}
			}).catch(err => {
			 	console.log(err);
			});
  	}


  	document.addEventListener('DOMContentLoaded', function() {
	    var elems = document.querySelectorAll('.sidenav');
	    var instances = M.Sidenav.init(elems, []);
	    // M.Collapsible.init(document.querySelector('.collapsible'));
	    M.FormSelect.init(document.querySelectorAll('select'));
	    M.Datepicker.init(document.querySelectorAll('.datepicker'),{format:'yyyy-mm-dd',
	    	maxDate: new Date(),
	    	defaultDate: new Date(),
	    	setDefaultDate:<?=isset($report['riqi'])?'false':'true';?>,
	    	showClearBtn:true,
	    	autoClose:true,
	    	i18n:{
      cancel: '取消',
      clear: '清除',
      done: '确认',
      previousMonth: '‹',
      nextMonth: '›',
      months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      monthsShort:  ['1 月', '2 月', '3 月', '4 月', '5 月', '6 月', '7 月', '8 月', '9 月', '10 月', '11 月', '12 月'],
      weekdays: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      weekdaysShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      weekdaysAbbrev: ['日', '一', '二', '三', '四', '五', '六'], 
    }});
	  });
  </script>
</body>
</html>